//
//  SMAddSaveMoneyTableViewController.m
//  SaveMoney
//
//  Created by user on 2018/11/23.
//  Copyright © 2018年 Sunflower. All rights reserved.
//

#import "SMAddSaveMoneyTableViewController.h"

#import "XWInteractiveTransition.h"
#import "XWPresentOneTransition.h"
#import "SBBaseButton.h"
#import "UIAlertController+Blocks.h"
#import "ActionSheetPicker.h"
#import "DNK_ImageClippingManager.h"

@interface SMAddSaveMoneyTableViewController ()<UIViewControllerTransitioningDelegate, UIGestureRecognizerDelegate, UITextFieldDelegate,DNKImageClippingDelegate>

@property (nonatomic, strong) XWInteractiveTransition *interactiveDismiss;
@property (nonatomic, strong) XWInteractiveTransition *interactivePush;

@property (weak, nonatomic) IBOutlet UILabel *modeLabel;
@property (weak, nonatomic) IBOutlet UITextField *oneTextF;
@property (weak, nonatomic) IBOutlet UITextField *twoTF;
@property (weak, nonatomic) IBOutlet UITextField *threeTF;
@property (weak, nonatomic) IBOutlet UITextField *fourTF;
@property (weak, nonatomic) IBOutlet SBBaseButton *backImage;

@property (nonatomic, copy) NSString *imageEncode;
@property (nonatomic, assign) SMMoneyType savaType;

@end

@implementation SMAddSaveMoneyTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
    UIWindow *windows = [UIApplication sharedApplication].keyWindow;
    tap.delegate = self;
    [windows addGestureRecognizer:tap];
    
    _oneTextF.delegate = self;
    _modeLabel.text = @"每天固定金额";
    self.savaType = 0;
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == _oneTextF) {
        NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if (toBeString.length > 6 && range.length!=1){
            textField.text = [toBeString substringToIndex:6];
            return NO;
        }
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak typeof(self) weakSelf = self;
    if (indexPath.row == 0) {
        [ActionSheetStringPicker showPickerWithTitle:@"请选择存钱模式" rows:@[@"目标期间每天固定金额",@"目标期间不固定存钱",@"无目标自由存钱"] initialSelection:0 doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
            
            weakSelf.savaType = selectedIndex;
           
            weakSelf.modeLabel.text = selectedValue;
            
            if (weakSelf.savaType == SMEverFreedom) {
                weakSelf.twoTF.text = @"自由存钱";
                weakSelf.threeTF.text = @"自由天数";
                [weakSelf.twoTF setUserInteractionEnabled:NO];
                [weakSelf.threeTF setUserInteractionEnabled:NO];
            } else {
                weakSelf.twoTF.text = @"";
                weakSelf.threeTF.text = @"";
                [weakSelf.twoTF setUserInteractionEnabled:YES];
                [weakSelf.threeTF setUserInteractionEnabled:YES];
            }
            
        } cancelBlock:^(ActionSheetStringPicker *picker) {
            
        } origin:tableView];
        
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    UIWindow *windows = [UIApplication sharedApplication].keyWindow;
    CGPoint curp = [touch locationInView:windows];
    if (curp.y >= SBIPHONEHEIGHT-SBIPHONEHEIGHT/1.5) {
        
        return NO;
    }else{
        if (![_oneTextF.text isEqualToString:@""] ||
            ![_twoTF.text isEqualToString:@""] ||
            ![_threeTF.text isEqualToString:@""]) {
            
            [UIAlertController showAlertInViewController:self withTitle:@"是否退出保存" message:@"" cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil tapBlock:^(UIAlertController * _Nonnull controller, UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
                if (action.style != UIAlertActionStyleCancel) {
                    [self dismiss];
                }
            }];
            return NO;
        }
        return YES;
    }
}


- (IBAction)addPhotoAction:(UIButton *)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择照片来源" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[DNK_ImageClippingManager shareManager] getImageFromIpc:UIImagePickerControllerSourceTypePhotoLibrary viewController:self];
        [DNK_ImageClippingManager shareManager].delegate = self;
    }];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[DNK_ImageClippingManager shareManager] getImageFromIpc:UIImagePickerControllerSourceTypeCamera viewController:self];
        [DNK_ImageClippingManager shareManager].delegate = self;
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:action];
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (IBAction)overAction:(SBBaseButton *)sender {
    
    if ([_oneTextF.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入存钱的目的性描述"];
        return;
    }
    
    if (_savaType != SMEverFreedom) {
        if ([_twoTF.text isEqualToString:@""]) {
            [SVProgressHUD showErrorWithStatus:@"请输入需要存钱的总金额"];
            return;
        }
        if ([_threeTF.text isEqualToString:@""] || [_threeTF.text isEqualToString:@"0"]) {
            [SVProgressHUD showErrorWithStatus:@"请输入存钱天数不小于1"];
            return;
        }
    } else {
        _twoTF.text = 0;
        _threeTF.text = 0;
    }
    
    if ([_fourTF.text isEqualToString:@""]) {
        _fourTF.text = @"0"; 
    }
    
    NSInteger total = [_twoTF.text intValue];
    NSInteger dataCount = [_threeTF.text intValue];
    NSInteger haveMoney = [_fourTF.text intValue];
    
    NSInteger dayMoney = 0;
    
    if (_savaType != SMEverFreedom) {
        if (haveMoney > total) {
            [SVProgressHUD showErrorWithStatus:@"预存金额大于目标总金额"];
            return;
        }
        dayMoney = (total-haveMoney) / dataCount;
    } else {
        total = haveMoney;
    }
     
    [SVProgressHUD show];
    
    SMMoneyModel *model = [[SMMoneyModel alloc] init];
    
    model.saveMoneyType = _savaType;
    model.saveMoneyTitle = _oneTextF.text;
    model.totalMoney = total;
    model.saveMoneyDay = dataCount;
    model.alreadyMoney = haveMoney;
    model.everyDayMoney = dayMoney;
    model.backImage = _imageEncode;
    model.creationTime = [NSString getNowTime];
    model.userKey = [SMUserInfoModel sharedStorage].userKey;
    
    [model save];
    
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
        [weakSelf dismiss];
    });
    
}

#pragma mark - ImageCropperDelegate
- (void)imageCropperdidFinished:(UIImage *)editedImage {
    
    [_backImage setImage:editedImage forState:UIControlStateNormal];
    
    UIImage *image = [self scaleToSize:editedImage size:CGSizeMake(SBIPHONEWIDTH, SBScaleNumber(200))];
    NSString *encode = [UIImage imageChangeBasr64StringWithImage:image];
    
    _imageEncode = encode;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SBScaleNumber(60);
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.transitioningDelegate = self;
        self.modalPresentationStyle = UIModalPresentationCustom;
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.transitioningDelegate = self;
        self.modalPresentationStyle = UIModalPresentationCustom;
    }
    return self;
}

- (void)dismiss{
    if (_delegate && [_delegate respondsToSelector:@selector(presentedOneControllerPressedDissmiss)]) {
        [_delegate presentedOneControllerPressedDissmiss];
    }
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    return [XWPresentOneTransition transitionWithTransitionType:XWPresentOneTransitionTypePresent];
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    return [XWPresentOneTransition transitionWithTransitionType:XWPresentOneTransitionTypeDismiss];
}

- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id<UIViewControllerAnimatedTransitioning>)animator{
    return _interactiveDismiss.interation ? _interactiveDismiss : nil;
}

- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id<UIViewControllerAnimatedTransitioning>)animator{
    XWInteractiveTransition *interactivePresent = [_delegate interactiveTransitionForPresent];
    return interactivePresent.interation ? interactivePresent : nil;
}

- (void)drawShadowWithView:(UIView *)View {
     
    //v.layer.masksToBounds=YES;这行去掉
    View.layer.cornerRadius = SBScaleNumber(20);
    View.layer.shadowColor = [UIColor blackColor].CGColor;
    View.layer.shadowOffset = CGSizeMake(2, 5);
    View.layer.shadowOpacity = 1.0;
    View.layer.shadowRadius = 10;
}

- (UIImage *)scaleToSize:(UIImage *)image size:(CGSize)size {
    //创建一个bitmap的context
    //并把他设置成当前的context
    UIGraphicsBeginImageContext(size);
    //绘制图片的大小
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    //从当前context中创建一个改变大小后的图片
    UIImage *endImage=UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return endImage;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
